package com.sctvcloud.bazhong.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gridsum.tracker.GridsumWebDissector;
import com.iflytek.cloud.thirdparty.V;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.application.Constances;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.beans.AFileItem;
import com.sctvcloud.bazhong.beans.LiveItem;
import com.sctvcloud.bazhong.beans.NewsItem;
import com.sctvcloud.bazhong.beans.SearchDataBean;
import com.sctvcloud.bazhong.beans.SearchKeyWords;
import com.sctvcloud.bazhong.beans.SearchResult;
import com.sctvcloud.bazhong.beans.TopicItem;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.tts.SpeachUtils;
import com.sctvcloud.bazhong.ui.adapter.SearchNewsAdapter;
import com.sctvcloud.bazhong.ui.adapter.SearchResultAdapter;
import com.sctvcloud.bazhong.ui.util.IListShowData;
import com.sctvcloud.bazhong.ui.utils.GlideUtil;
import com.sctvcloud.bazhong.ui.utils.KeyBoardUtils;
import com.sctvcloud.bazhong.ui.utils.SkipUtil;
import com.sctvcloud.bazhong.ui.widget.MyStellarMap;
import com.sctvcloud.bazhong.ui.widget.RecyclerViewEx;
import com.sctvcloud.bazhong.ui.widget.VoiceLongPressView;
import com.shitou.googleplay.lib.randomlayout.StellarMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchNewsActivity extends BaseActivity implements SpeachUtils.OnVoiceRecordListener, SearchNewsAdapter.OnItemBtnClick {
    @BindView(R.id.search_notes_layout)
    protected LinearLayout search_note;
    @BindView(R.id.search_news_layout)
    protected LinearLayout search_news;
    @BindView(R.id.news_list)
    protected RecyclerViewEx newsListView;
    @BindView(R.id.search_key_ct)
    protected CustomFontEditText search_ct;
    //    @BindView(R.id.search_view_ll)
//    protected LinearLayout view_ll;
    @BindView(R.id.search_notes)
    protected CustomFontTextView searchNotes;
    @BindView(R.id.search_status_txt)
    protected CustomFontTextView searchStatusTxt;
    @BindView(R.id.stellar_map)
    protected MyStellarMap stellarMap;
    @BindView(R.id.voice_bg)
    protected ImageView voiceBg;
    @BindView(R.id.voice_search)
    protected VoiceLongPressView voiceLongPress;
    private List<SearchDataBean> dataList = new ArrayList<>();
    List<IListShowData> tempNewsList = new ArrayList<>();
    private SpeachUtils speachUtils;
    private SearchNewsAdapter adapter;
    private ArrayList<String> hotList = new ArrayList<String>();
    private String searchKey = "";
    private static final long SPACE = 200;
    private int volume = 0;
    private AnimationDrawable voiceIconAnimation;

    private boolean isAddMore = false;
    private int count = 0;
    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        getHotList();//初始化数据
        initVoiceLongPress();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search_news);
        ButterKnife.bind(this);
    }

    private void initView() {
        newsListView.setLayoutManager(new LinearLayoutManager(this));
        searchNotes.setText("Hi~我是智能助手观观，您可以问我");
        searchStatusTxt.setText("长按说话");
        adapter = new SearchNewsAdapter(this, dataList, this);
        newsListView.setAdapter(adapter);
    }


    private void initVoiceLongPress() {
        voiceLongPress.setLongClickListener(new VoiceLongPressView.OnLongVoiceClickListener() {
            @Override
            public void onLongClick() {
                search_note.setVisibility(View.VISIBLE);
                search_news.setVisibility(View.GONE);
                //获取 AnimationDrawable
                voiceIconAnimation = (AnimationDrawable) voiceBg.getDrawable();
                voiceIconAnimation.start();
                speachUtils = new SpeachUtils(SearchNewsActivity.this);
                speachUtils.setVoiceRecordListener(SearchNewsActivity.this);
                JLog.e("VoiceLongPressView --- ", "OnPressDown");
                voiceLongPress.setImageResource(R.mipmap.search_voice_press);
                searchNotes.setText("我正在听，请说话...");
                searchStatusTxt.setText("松开完成");
                stellarMap.setVisibility(View.GONE);
                speachUtils.startRecord();
            }

            @Override
            public void onClickUp() {
                voiceIconAnimation = (AnimationDrawable) voiceBg.getDrawable();
                voiceIconAnimation.stop();
                voiceIconAnimation.selectDrawable(0);
                voiceLongPress.setImageResource(R.mipmap.search_voice);
                searchNotes.setText("Hi~我是智能助手观观，您可以问我");
                searchStatusTxt.setText("长按说话");
                speachUtils.stopRecord();
                if (ListUtils.isListValued(dataList)) {
                    search_note.setVisibility(View.GONE);
                    search_news.setVisibility(View.VISIBLE);
                }
                JLog.e("VoiceLongPressView --- ", "OnPressUp   ");
            }
        });
    }

    @Override
    public void OnRecordBack(String txt) {
        JLog.e("VoiceLongPressView --- ", " voiceStr = " + txt);
        if (!txt.endsWith("。") && !txt.endsWith("！") && !txt.endsWith("？")) {
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "主动搜索"));
            GridsumWebDissector.getInstance().trackEvent(this, "", "语音搜索", "", 200, pairs);
            search(txt);
        }
    }

    /**
     * 初始化热门搜索view
     */
    private void initHotView() {
//        stellarMap = new StellarMap(this);
        // 1.设置内部的TextView距离四周的内边距
        int padding = 10;
        stellarMap.setInnerPadding(padding, padding, padding, padding);
        stellarMap.setAdapter(new StellarMapAdapter());
        // 设置默认显示第几组的数据
        stellarMap.setGroup(0, true);// 这里默认显示第0组
        // 设置x和y方向上的显示的密度
        stellarMap.setRegularity(4, 6);// 如果值设置的过大，有可能造成子View摆放比较稀疏
    }

    /**
     * 点击搜索按钮，搜索关键词相关
     *
     * @param keyword
     */
    private void search(String keyword) {
        search_note.setVisibility(View.GONE);
        search_news.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(keyword)) {
            dataList.add(new SearchDataBean(SearchNewsAdapter.INPUT_KEY_TYPE, keyword, null));
            dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_ING, "正在搜索...", null));
            if (adapter != null) {
                int position = adapter.setDataList(dataList);
                newsListView.scrollToPosition(position);
            }
        } else {
            dataList.add(new SearchDataBean(SearchNewsAdapter.NOTES_TYPE, "您输入的关键词为空", null));
            if (adapter != null) {
                int position = adapter.setDataList(dataList);
                newsListView.scrollToPosition(position);
            }
            return;
        }
        searchKey = keyword;
        JLog.e("VoiceLongPressView --- ", " search voiceStr = " + keyword);
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", 0);
        param.put("option", 0);
        param.put("count", 10);
        final long searchTime = System.currentTimeMillis();
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(final SearchResult fSearch) {
                long delay = 1500 - (System.currentTimeMillis() - searchTime);
                if (delay > 0) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (fSearch != null && (ListUtils.isListValued(fSearch.getAnchorList()) || ListUtils.isListValued(fSearch.getLiveList()) || ListUtils.isListValued(fSearch.getNewsList()) || ListUtils.isListValued(fSearch.getSpecialList()))) {
                                JLog.e("=====search==" + fSearch.toString());
                                setSearchData(fSearch);
                            } else {
                                setSearchData(null);
                            }
                        }
                    }, delay);
                } else {
                    if (fSearch != null && (ListUtils.isListValued(fSearch.getAnchorList()) || ListUtils.isListValued(fSearch.getLiveList()) || ListUtils.isListValued(fSearch.getNewsList()) || ListUtils.isListValued(fSearch.getSpecialList()))) {
                        JLog.e("=====search==" + fSearch.toString());
                        setSearchData(fSearch);
                    } else {
                        setSearchData(null);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
//                onNetFinish();
            }
        });
    }

    /**
     * 获取热门搜索数据
     */
    private void getHotList() {
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        NetUtils.getNetAdapter().getHotKeyWords(getOwnerName(), param, new AbsNetCallBack<SearchKeyWords>(SearchKeyWords.class) {
            @Override
            public void onSuc(SearchKeyWords searchKeyWords) {
                if (searchKeyWords != null) {
                    if (!TextUtils.isEmpty(searchKeyWords.getKeywords())) {
                        String[] keyWordsList = searchKeyWords.getKeywords().split(",");
                        if (null != keyWordsList) {
                            for (int i = 0; i < keyWordsList.length; i++) {
                                hotList.add(keyWordsList[i]);
                            }
                            initHotView();
                        }
                    }
                }
            }
        });
    }


    /**
     * 赋值显示搜索结果
     *
     * @param fSearches
     */
    private void setSearchData(final SearchResult fSearches) {
        isAddMore = false;
        count = 0;
        if (null != dataList && dataList.size() > 1) {
            if (adapter != null) {
                dataList.remove(dataList.size() - 1);
                adapter.setMoreNewsList(dataList);
            }
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != fSearches) {
                    dataList.add(new SearchDataBean(SearchNewsAdapter.NOTES_TYPE, "观观为您搜索到以下内容：", null));
                    List<NewsItem> newsList = fSearches.getNewsList();
        //          List<FProgram> programmeList = fSearches.getProgrammeList();
                    List<LiveItem> liveList = fSearches.getLiveList();
        //          List<AFileItem> anchorList = fSearches.getAnchorList();
                    List<TopicItem> specialList = fSearches.getSpecialList();
                    if (ListUtils.isListValued(newsList)) {
                        if (newsList.size() > 3) {
                            for (int i = 0; i < 3; i++) {
                                count++;
                                dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", newsList.get(i)));
                            }
                            dataList.add(new SearchDataBean(SearchNewsAdapter.LOAD_MORE_TYPE, searchKey, null));
                            isAddMore = true;
                        } else {
                            for (int i = 0; i < newsList.size(); i++) {
                                count++;
                                dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", newsList.get(i)));
                            }
                        }
                    }
                    if (count < 3) {
                        if (ListUtils.isListValued(specialList)) {
                            int sCount = 3 - count;
                            if (specialList.size() > sCount) {
                                for (int i = 0; i < sCount; i++) {
                                    count++;
                                    dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", specialList.get(i)));
                                }
                                dataList.add(new SearchDataBean(SearchNewsAdapter.LOAD_MORE_TYPE, searchKey, null));
                                isAddMore = true;
                            } else {
                                for (int i = 0; i < specialList.size(); i++) {
                                    count++;
                                    dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", specialList.get(i)));
                                }
                            }
                        }
                    } else if (count == 3 && !isAddMore) {
                        if (ListUtils.isListValued(specialList)) {
                            dataList.add(new SearchDataBean(SearchNewsAdapter.LOAD_MORE_TYPE, searchKey, null));
                            isAddMore = true;
                        }
                    }
                    if (count < 3) {
                        if (ListUtils.isListValued(liveList)) {
                            int lCount = 3 - count;
                            if (liveList.size() > lCount) {
                                for (int i = 0; i < lCount; i++) {
                                    count++;
                                    dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", liveList.get(i)));
                                }
                                dataList.add(new SearchDataBean(SearchNewsAdapter.LOAD_MORE_TYPE, searchKey, null));
                                isAddMore = true;
                            } else {
                                for (int i = 0; i < liveList.size(); i++) {
                                    count++;
                                    dataList.add(new SearchDataBean(SearchNewsAdapter.SEARCH_RESULT_TYPE, "", liveList.get(i)));
                                }
                            }
                        }
                    } else if (count == 3 && !isAddMore) {
                        if (ListUtils.isListValued(liveList)) {
                            dataList.add(new SearchDataBean(SearchNewsAdapter.LOAD_MORE_TYPE, searchKey, null));
                            isAddMore = true;
                        }
                    }
                } else {
                    dataList.add(new SearchDataBean(SearchNewsAdapter.NOTES_TYPE, "抱歉，没有找到相关新闻", null));
                }

                if (adapter != null) {
                    int position = adapter.setDataList(dataList);
                    if (isAddMore) {
                        newsListView.scrollToPosition(position - 2);
                    } else if (position > 1 && count == 3) {
                        newsListView.scrollToPosition(position - 1);
                    } else {
                        newsListView.scrollToPosition(position);
                    }
                }
            }
        }, 10);
    }

    @Override
    public void onItemBtnClick(IListShowData data) {
        if (data instanceof NewsItem) {
            NewsItem item = (NewsItem) data;
            SkipUtil.skipWithNewsItem(this, item, new HashMap<String, String>());
        } else if (data instanceof LiveItem) {
            LiveItem item = (LiveItem) data;
            Intent intent = new Intent(this, LivingActivity.class);
            intent.putExtra(BaseActivity.EX_URL, item.getLiveContentUrl());
            intent.putExtra(BaseActivity.EX_DATA, item.getLiveImg());
            startActivity(intent);
        } else if (data instanceof TopicItem) {
            TopicItem item = (TopicItem) data;
            Intent intent = new Intent(this, TopicDetailActivity.class);
            intent.putExtra(BaseActivity.EX_URL, item.getNewsUrl());
            startActivity(intent);
        }
    }

    @Override
    public void onLoadMore(String keyword) {
        if (!TextUtils.isEmpty(searchKey)) {
            Intent intent = new Intent(this, SearchResultMoreActivity.class);
            intent.putExtra(SearchResultMoreActivity.SEARCH_KEY, keyword);
            startActivity(intent);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            String key = search_ct.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("搜索关键词不能为空");
                return false;
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "主动搜索"));
            GridsumWebDissector.getInstance().trackEvent(this, "", "输入搜索", "", 200, pairs);
            search(key);
        }
        return super.dispatchKeyEvent(event);
    }

    @OnClick(value = {R.id.voice_search, R.id.search_cancel})
    public void speakClick(View view) {
        switch (view.getId()) {
            case R.id.voice_search:

                break;
            case R.id.search_cancel:
                super.onBackPressed();
                break;
        }
    }


    class StellarMapAdapter implements StellarMap.Adapter {
        /**
         * 返回多少组数据
         */
        @Override
        public int getGroupCount() {
            return 1;
        }

        /**
         * 每组多少个数据
         */
        @Override
        public int getCount(int group) {
            if (null != hotList) {
                return hotList.size();
            } else {
                return 0;
            }
        }

        /**
         * group: 当前是第几组 position:是当前组的position
         */
        @Override
        public View getView(int group, int position, View convertView) {
            final TextView textView = new TextView(SearchNewsActivity.this);
            // 根据group和组中的position计算出对应的在list中的位置
//            int listPosition = group * getCount(group) + position;
            textView.setText(hotList.get(position));
            // 1.设置随机的字体大小(随机大小)
            Random random = new Random();
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                    random.nextInt(10) + 10);// 14-29
            // 2.上色，设置随机的字体颜色
            // 如果三原色的值过大会偏白色，过小会偏黑色，所以应该随机一个中间的颜色的值
            int alpha = random.nextInt(120) + 80;// 50-199
            int red = 225;//random.nextInt(150) + 50;// 50-199
            int green = 124;//random.nextInt(150) + 50;// 50-199
            int blue = 104;//random.nextInt(150) + 50;// 50-199
            int textColor = Color.argb(alpha, red, green, blue);// 在rgb三原色的基础上混合出一种新的颜色
            textView.setTextColor(textColor);
            return textView;
        }

        // 虽然定义了，但是并没有什么乱用
        @Override
        public int getNextGroupOnPan(int group, float degree) {
            return 0;
        }

        // 当前组缩放完成之后下一组加载哪一组的数据 group： 表示当前是第几组
        @Override
        public int getNextGroupOnZoom(int group, boolean isZoomIn) {
            // 0->1->2->0
            return 0;
        }
    }

}
